package mysql

import (
	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	GoodsTitle  string  `gorm:"type:varchar(50);index;not null;comment:商品标题;"`
	GoodsPrice  float64 `gorm:"type:decimal(10,2);default:0;comment:商品价格;"`
	GoodsStock  int64   `gorm:"type:int(10);default:0;comment:商品库存;"`
	GoodsStatus int64   `gorm:"type:tinyint(1);comment:1代表上架 0代表下架;"`
	GoodsCover  string  `gorm:"type:varchar(255);index;not null;comment:商品图片;"`
}

// 新增
func (g *Goods) Create() error {
	return DB.Create(&g).Error
}

func (g *Goods) GoodsList(keyword string, page, size int) ([]*Goods, error) {
	var list []*Goods
	err = DB.Where("goods_title like ?", "%"+keyword+"%").Scopes(Paginate(page, size)).Order("goods_price desc, created_at desc").Find(&list).Error
	return list, err
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// 商品详情
func (g *Goods) Detail(goodsId int64) error {
	return DB.Where("id = ?", goodsId).First(&g).Error
}
